#include "moneymove.h"

#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>


#include <QSqlRecord>
#include <QSqlQuery>
#include <QSqlError>
#include <QDate>
#include <QDebug>

#include "../components/numpad.h"

#include "../settings.h"
#include "../service.h"
#include "../definitions.h"

MoneyMove::MoneyMove(const QString& params, QWidget *parent) :
    FormInterface(parent)
{
    this->params = params;

    QGridLayout *mainLayout = new QGridLayout(this);

    QSettings *settings = Settings::getInstance();

    model = new QSqlQueryModel(this);
    model->setQuery(settings->value("queries/moneymove/movslist").toString());
    model->setHeaderData(0, Qt::Horizontal, "Операции");

    view = new QTableView(this);
    view->setModel(model);

    view->hideColumn(1);

    QHeaderView *header = view->verticalHeader();
    header->setDefaultSectionSize(settings->value("globals/table_height").toInt());
    header->setVisible(false);

    header = view->horizontalHeader();
    header->setStretchLastSection(true);
    //  view->horizontalHeader()->setVisible(false);

    view->setFocusPolicy(Qt::NoFocus);

    mainLayout->addWidget(view,0,0);

    QVBoxLayout *numpadLayout = new QVBoxLayout();
    Numpad *npad = new Numpad(this);

    numpadLayout->addWidget(npad);
    numpadLayout->addStretch(1);

    mainLayout->addLayout(numpadLayout,0,1);

    connect(npad, SIGNAL(inputCommited(QString)),
            this, SLOT(summCommited(QString)));

    totals = new QLabel(this);
    mainLayout->addWidget(totals,1,0);

    updateTotals();

    setFocusProxy(npad);
}


void MoneyMove::updateTotals(){
    QString text;// = "<h1>Свод по кассе</h1><br>";

    QSqlQuery query;
    double summOnStart = 0;

    QDate start_date = QDate(2000,1,1);
    QTime start_time = QTime(0,0,0);

    QSettings *settings = Settings::getInstance();

    query.prepare(settings->value("queries/moneymove/first_pair_document").toString());
    query.bindValue(":store", Settings::getDefinition("ТЕКУЩАЯ_БАЗА").toInt());
    query.bindValue(":user", Settings::getVariables()->value("user_id").toInt());

    if(!query.exec()){
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
    }else {
        if(query.next()){
            start_date = query.value(0).toDate();
            start_time = query.value(1).toTime();
        }
    }

    text = "Смена с "+start_date.toString("dd.MM.yyyy")+" "+start_time.toString("hh:mm:ss");

    text += "<h2>Товарные операции</h2>";
    query.prepare(settings->value("queries/moneymove/goods_operations_sum").toString());
    query.bindValue(":time_start",start_time);
    query.bindValue(":date_start",start_date);
    query.bindValue(":date_start2",start_date);

    if(!query.exec()){
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
    }
    while (query.next()) {
        text += "<li>"+query.value(0).toString() + ": "+ QString::number(query.value(1).toDouble(),'f',2);
        summOnStart += query.value(1).toDouble();
    }

    text += "<h2>Денежные операции</h2>";
    query.prepare(settings->value("queries/moneymove/money_operations_sum").toString());
    query.bindValue(":time_start",start_time);
    query.bindValue(":date_start",start_date);
    query.bindValue(":date_start2",start_date);
    if(!query.exec()){
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
    }
    while (query.next()) {
        text += "<li>"+query.value(0).toString() + ": "+ QString::number(query.value(1).toDouble(),'f',2);
        summOnStart -= query.value(1).toDouble();
    }

    query.prepare(settings->value("queries/moneymove/rests_in_kassa_sum").toString());
    query.bindValue(":store", Settings::getDefinition("ТЕКУЩАЯ_БАЗА").toInt());
    query.bindValue(":user", Settings::getVariables()->value("user_id").toInt());

    if(!query.exec()){
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
    }
    while (query.next()) {
        text += "<h2>Остаток в кассе: "+ QString::number(query.value(0).toDouble(),'f',2)+"</h2>";
        summOnStart += query.value(0).toDouble();
    }

    totals->setText(text);
}

void MoneyMove::summCommited(const QString &text)
{
    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    int row = view->currentIndex().row();
    QSqlRecord record = model->record(row);

    int operation_id = record.value(1).toInt();

    QSqlQuery query;
    QSettings *settings = Settings::getInstance();

    query.prepare(settings->value("queries/moneymove/get_section_id").toString());
    query.bindValue(":operation_id", operation_id);
    if(!query.exec()){
        db.rollback();
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
        return;
    }

    query.next();
    int section_id = query.value(0).toInt();

    query.prepare(settings->value("queries/moneymove/get_new_document_id").toString());
    if(!query.exec()){
        db.rollback();
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
        return;
    }

    query.next();
    int doc_id = query.value(0).toInt();

    query.prepare(settings->value("queries/moneymove/save_document").toString());
    //:id,:data,:section_id,:operation_id,:store,:user
    query.bindValue(":id", doc_id);
    query.bindValue(":data", QDate::currentDate());
    query.bindValue(":section_id", section_id);
    query.bindValue(":operation_id", operation_id);
    query.bindValue(":summ", text.toDouble());
    query.bindValue(":store", Settings::getDefinition("ТЕКУЩАЯ_БАЗА").toInt());
    query.bindValue(":user", Settings::getVariables()->value("user_id").toInt());

    if(!query.exec()){
        db.rollback();
        qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();
        return;
    }

    db.commit();

    updateTotals();

}
